<template>
    <el-dialog
      v-model="visibleUpdate"
      :title="params.title"
      width="50%"
      align-center
      :before-close="handleClose"
    >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
      :disabled="params.type == 'details'"
    >
      <el-form-item 
        label="图书id"
        prop="book_id" 
        v-show="params.type != 'add'"
      >
        <el-input v-model="ruleForm.book_id"  disabled/>
      </el-form-item>
      <el-form-item label="图书名称" prop="book_name">
        <el-input v-model="ruleForm.book_name" :disabled="params.type != 'add'" />
      </el-form-item>
      <el-form-item label="作者" prop="author" >
        <el-input v-model="ruleForm.author" />
      </el-form-item>
      <el-form-item label="ISBN" prop="isbn">
        <el-input v-model="ruleForm.isbn"  />
      </el-form-item>
      <el-form-item label="出版社" prop="publisher">
        <el-input v-model="ruleForm.publisher" />
      </el-form-item>
      <el-form-item label="图书简介" prop="briefIntro">
        <el-input
          v-model="ruleForm.briefIntro"
          :rows="2"
          type="textarea"
          placeholder="请输入图书简介"
        />
      </el-form-item>
      <el-form-item label="图书分类" prop="category_id">
        <el-select 
          v-model="ruleForm.category_id" 
          class="m-2" 
          placeholder="下拉选择图书分类"
          @change="selCategory"
        >
          <el-option
            v-for="item in cateGoryList"
            :key="item.category_id"
            :label="item.category_name"
            :value="item.category_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否上架" prop="statuss">
        <el-radio-group v-model="ruleForm.statuss">
          <el-radio :label="0">未上架</el-radio>
          <el-radio :label="1">已上架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="单价" prop="price">
        <el-input v-model="ruleForm.price" />
      </el-form-item>
      <el-form-item label="销量" prop="sales">
        <el-input v-model="ruleForm.sales" />
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input v-model="ruleForm.stock" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button 
          @click="handlerClick('cancel')"
        >
          取消
        </el-button>
        <el-button 
          type="primary" 
          v-if="params.type != 'details'"
          @click="handlerClick('confirm', ruleFormRef)"
        >
          提交
        </el-button>
      </span>
    </template>

    </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex';
import bookModelApi from '@/request/api/book.js';
import { onBeforeMount, onMounted, watchEffect } from 'vue';

const store = useStore();
const cateGoryList = store.state.book.cateGoryList;

// 接收值
const props = defineProps({
  params: {
    type: Object,
    default: {}
  },
  visibleUpdate: {
    type: Boolean,
    default: false
  }
})

const { params, visibleUpdate } = toRefs(props);

const ruleFormRef = ref()
// 表单绑定属性值model
let ruleForm = ref({
  book_name: '',
  author: '',
  isbn: '',
  publisher: '',
  briefIntro: '',
  category_id: '',
  statuss: 1,
  price: '',
  sales: '',
  stock: '',

  category_name: '',
  status_name: ''
})

// 校验规则
const rules = reactive({
  book_name: [
    { required: true, message: '请填写图书名称', trigger: 'blur' },
  ],
  author: [
    { required: true, message: '请填写作者', trigger: 'blur' },
  ],
  isbn: [
    { required: true, message: '请填写ISBN', trigger: 'blur' },
    { min: 13, max: 13, message: 'ISBN长度为13位', trigger: 'blur' },
  ],
  publisher: [
    { required: true, message: '请填写出版社', trigger: 'blur' },
  ],
  briefIntro: [
    { required: true, message: '请输入图书简介', trigger: 'blur' },
  ],
  category_id: [
    { required: true, message: '请选择图书分类', trigger: 'blur' },
  ],
  statuss: [
  ],
  price: [
    { required: true, message: '请填写图书单价', trigger: 'blur' },
  ],
  sales: [
    { required: true, message: '请填写图书单价', trigger: 'blur' },
  ],
  stock: [
    { required: true, message: '请填写图书库存', trigger: 'blur' },
  ]
})

// 点击外部区域关闭提示
const handleClose = ( done ) => {
  ElMessageBox.confirm('确定关闭此对话框吗?')
    .then(() => {
      handlerClick('cancel')
    })
    .catch(() => {
      // catch error
    })
}

// 监听器 点击详情或者编辑数据回显
watch(() => props.params, (newVal, oldVal) => {
    if (newVal.data) {
      // 详情或编辑
      // 浅拷贝
      for(let key in newVal.data){
        ruleForm.value[key] = newVal.data[key]
      }
      // ruleForm = newVal.data; 
    }else{
      // 新增
      ruleForm = ref({
        book_name: '',
        author: '',
        isbn: '',
        publisher: '',
        briefIntro: '',
        category_id: '',
        statuss: 1,
        price: '',
        sales: '',
        stock: '',

        category_name: '',
        status_name: ''
      })
    }
}, { deep: true })

// 子传父亲
const emits = defineEmits(['confirm']);
const handlerClick = ( type, formEl ) => {
  // 此时 params.value.data 就是选中的那一行图书对象
  if( type == 'confirm' ){
    clickUpdate( type, formEl )
  }else{
    ElMessage({
      showClose: true,
      message: '取消操作',
      type: 'warning',
    })
  }
  // 传递到父组件通知关闭
  emits('confirm', { type });
}

// 点击新增或者修改
async function clickUpdate( type, formEl){
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      updateBook();
      // 传递到父组件通知关闭
      setTimeout(() => {
        emits('confirm', { type });
      }, 200)

      // new Promise(resolve => {
      //   emits('confirm', { type });
      //   resolve();
      // })
      
    } else {
      ElMessage({
        showClose: true,
        message: '校验失败,请填写正确且完整的内容',
        type: 'error',
      })
    }
  })
}

function updateBook(){

  if( params.value.type  == 'add' ){
    // 调用新增接口
    let p = {
      ...ruleForm.value,
      category_id: +ruleForm.value.category_id,
      price: +ruleForm.value.price,
      sales: +ruleForm.value.sales,
      stock: +ruleForm.value.stock,
    }
    bookModelApi.addBookApi( p ).then(res => {
      ElMessage({
        showClose: true,
        message: res.msg,
        type: 'success',
      })
    }).catch(err => {

    })
  }

  if( params.value.type  == 'update' ){
    // 调用修改接口
    bookModelApi.updateBookApi( ruleForm.value ).then(res => {
      ElMessage({
        showClose: true,
        message: res.msg,
        type: 'success',
      })
    }).catch(err => {
      ElMessage({
        showClose: true,
        message: err,
        type: 'error',
      })
    })
    
  }
}

</script>

<style scoped lang="less">

</style>

